<template>
  <div class="mainBox">
    <!-- 查询 -->
      <div class="container">
        <el-row :gutter="20">
          <el-col :span="12">
            <span>用户组:</span>
            <el-select v-model="searchParam.group_id" clearable filterable placeholder="请选择">
              <el-option
                v-for="item in userGroupsArr"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
            <span>状态:</span>
            <el-select v-model="searchParam.status" clearable placeholder="请选择">
              <el-option
                v-for="item in statusArr"
                :key="item.value"
                :label="item.text"
                :value="item.value">
              </el-option>
            </el-select>
            <el-button type="primary" @click="getTasksList" size="small" icon="el-icon-search">查询</el-button>
          </el-col>
          <el-col :span="6" >
            <el-button  type="primary" @click="dialogFormVisible = true" size="small" icon="el-icon-plus">添加任务</el-button>
          </el-col>
        </el-row>
      </div>
    <!-- table -->
      <el-table
        :data="tasksTableData"
        border
        style="width: 100%">
        <el-table-column
          prop="id"
          label="ID"
          width="80"
          align="center">
        </el-table-column>
        <el-table-column
          prop="account.username"
          label="账户名称"
          width="200"
          align="center">
        </el-table-column>
        <el-table-column
          prop="mobile"
          label="手机号"
          width="120"
          align="center">
        </el-table-column>
        <el-table-column
          prop="create_at"
          label="创建时间"
          width="180"
          align="center">
        </el-table-column>
        <el-table-column
          label="呼叫次数"
          prop="call_num"
          align="center"
          >
        </el-table-column>
        <el-table-column
          label="间隔(秒)"
          prop="interval"
          align="center"
          >
        </el-table-column>
        <el-table-column
          label="任务进度"
          align="center"
          width="180">
            <template slot-scope="scope">
              <el-progress :text-inside="true" :stroke-width="18" :percentage="scope.row.percent" status="success"></el-progress>
            </template>
        </el-table-column>
        <el-table-column
          prop="message"
          label="内容"
          align="center">
        </el-table-column>
        <el-table-column
          prop="update_at"
          label="更新时间"
          width="180"
          align="center">
        </el-table-column>
        <el-table-column
          label="状态"
          width="120"
          align="center"
          >
            <template slot-scope="scope">
              <el-tag
                :type="scope.row.status | colorParseFilter"
                close-transition>{{scope.row.status | textParseFilter}}</el-tag>
            </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.status !== 'finished'">
                  <span v-if="scope.row.status === 'pending'">
                    <el-button
                      size="mini"
                      type="warning"
                      @click="taskOperFun(scope.$index, scope.row,'pause')">暂停</el-button>
                  </span>
                  <span v-else-if="scope.row.status === 'stopped'">
                    <el-button
                      size="mini"
                      type="success"
                      @click="taskOperFun(scope.$index, scope.row,'continue')">启动</el-button>
                  </span>
                  <span v-else>
                    <!--
                    <el-button
                      size="mini"
                      type=""
                      @click="handleEdit(scope.$index, scope.row)">{{scope.row.status | textParseFilter}}</el-button>
                    -->
                  </span>
            </span>
            <el-button
              size="mini"
              type="primary"
              @click="taskDetailFun(scope.$index, scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

          <!-- 分页 -->
          <div v-show="total" class="pagination-container" style="margin-top: 20px;">
              <el-pagination
                class="pagination-container" style="margin-top: 20px;"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[10,20,50,100]"
                :page-size="10"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
              </el-pagination>
          </div>


          <!-- dialog 添加用户-->
          <el-dialog title="任务" :visible.sync="dialogFormVisible" @close="closeDialog">
            <el-form :model="form" :rules="rules" ref="addUserForm" label-width="120px" style="">
              <el-form-item label="icloud用户名" prop="username">
                <el-input v-model="form.username" placeholder="请输入用户名" auto-complete="off"></el-input>
              </el-form-item>
              <el-form-item label="icloud密码" prop="password">
                <el-input v-model="form.password" placeholder="请输入密码" auto-complete="off"></el-input>
              </el-form-item>
              <el-form-item label="手机号" prop="mobile">
                <el-input v-model="form.mobile" placeholder="请输入手机号" auto-complete="off" :maxlength="11"></el-input>
              </el-form-item>
              <el-form-item label="时间间隔" prop="interval">
                <el-input v-model.number="form.interval" placeholder="请输入任务时间间隔" auto-complete="off">
                  <template slot="append">秒</template>
                </el-input>
              </el-form-item>
              <el-form-item label="任务次数" prop="call_num">
                <el-input v-model.number="form.call_num" placeholder="请输入任务次数" auto-complete="off"></el-input>
              </el-form-item>
              <el-form-item label="任务内容" prop="message">
                <el-input type="textarea" :rows="4" v-model="form.message"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitForm('addUserForm')">保存</el-button>
                <el-button @click="resetForm('addUserForm')">重置</el-button>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取 消</el-button>
              <!--<el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>-->
            </div>
          </el-dialog>

          <!-- 任务详情-->
          <el-dialog title="任务详情" :visible.sync="dialogTaskDetailVisible">
            <el-table :data="taskDetailList">
              <el-table-column property="id" label="ID" width="80" align="center"></el-table-column>
              <el-table-column property="create_at" label="创建时间" width="180" align="center"></el-table-column>
              <el-table-column property="duration" label="持续时间" width="180" align="center"></el-table-column>
              <el-table-column property="start_time" label="开始时间" width="180" align="center"></el-table-column>
              <el-table-column property="update_at" label="更新时间" width="180" align="center"></el-table-column>
              <el-table-column  label="状态" width="120" align="center">
                 <template slot-scope="scope">
                  <el-tag
                    :type="scope.row.status | colorParseFilter"
                    close-transition>{{scope.row.status | textParseFilter}}</el-tag>
                </template>
              </el-table-column>
            </el-table>
             <!-- 分页 -->
             <div v-show="taskDetail_total" class="pagination-container" style="margin-top: 20px;">
                <el-pagination
                  class="pagination-container" style="margin-top: 20px;"
                  @size-change="taskDetail_handleSizeChange"
                  @current-change="taskDetail_currentPage"
                  :current-page="taskDetailListForm.taskDetail_currentPage"
                  :page-sizes="[10,20,50,100]"
                  :page-size="10"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="taskDetail_total">
                </el-pagination>
             </div>

          </el-dialog>
  </div>
</template>


<script>
import {getUserGroup} from '@/api/userGroup'
import {getTasks,addTask,taskOper,taskDetail} from '@/api/tasks'
export default{
  data() {
    return {
      total:0,
      pageSize: 10,
      currentPage: 1,
      dialogFormVisible: false,
      form:{
        username: '',
        password:'',
        mobile: '',
        call_num: '',
        interval: '',
        message: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {validator:function(rule,value,callback){
              if (!(/^1[34578]\d{9}$/.test(value))) {
                  callback('手机号码格式错误');
              }else {
                  callback();
              }
          },trigger: 'blur'}
        ],
        call_num: [
          { required: true, message: '请输入任务次数', trigger: 'blur' },
          { type: 'number', message: '必须为数字值'}
        ],
        interval: [
          { required: true, message: '请输入任务间隔', trigger: 'blur' },
          { type: 'number', message: '手机号必须为数字值'}
        ],
        message: [
          { required: true, message: '请输入任务内容', trigger: 'blur' }
        ]
      },
      taskDetailId:'',
      status: '1',
      status_Boolean: true,
      searchParam:{
        status: '',
        group_id: '',
        per_page: 10,
        page: 1
      },
      statusArr:[
        {text:'等待',value:'pending'},
        {text:'暂停',value:'stopped'},
        {text:'完成',value:'finished'},
        {text:'成功',value:'success'},
        {text:'失败',value:'failed'}
      ],
      userGroupsArr:[],
      tasksTableData:[], //任务列表数据
      rolesArr:[], //角色下拉框
      taskDetailList: [], //详情list
      dialogTaskDetailVisible: false, //详情列表Dialog
      taskDetail_total: 0,
      taskDetailListForm:{
        taskDetail_per_page: 10,
        taskDetail_page: 1
      }

    }
  },
  created(){
    this.getTasksList();
    this.getUserGroupList();
  },
  methods: {
    //任务列表
    getTasksList(){
      getTasks(this.searchParam, response=> {
        const res = response.data
        if(res.code == 1){
          this.tasksTableData = (res.data).items
          this.total = (res.data).total
        }
      })
     },
    //获取用户组下拉框列表
    getUserGroupList(){
      getUserGroup({
        per_page: 1000
      },response=> {
        const res = response.data
        if(res.code == 1){
          this.userGroupsArr = (res.data).items
        }
      })
    },
    //保存
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
            this.addTaskFun()
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    //添加任务
    addTaskFun(){
      addTask(this.form, response=> {
        const res = response.data;
        if(res.code == 1){
          this.$message.success('添加成功')
          this.dialogFormVisible = false
          this.getTasksList();
        }
      })
    },
    //重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //任务暂停/开始
    taskOperFun(index, row, action){
      taskOper(row.id,{
        "action": action
      }, response=> {
        const res = response.data;
        if(res.code === 1){
          this.getTasksList();
        }
      })
    },
    //详情
    taskDetailFun(index, row) {
      // console.log(index, row);
      this.taskDetailId = row.id
      this.getDetailList();
      this.dialogTaskDetailVisible = true;
    },
    //获取详情页list
    getDetailList(){
      taskDetail(this.taskDetailId, this.taskDetailListForm, response=> {
        const res = (response.data);
        if(res.code === 1){
          this.taskDetailList = (res.data).items;
          this.taskDetail_total = (res.data).total;
        }
      })
    },
    taskDetail_handleSizeChange(val) {
      this.taskDetailListForm.taskDetail_per_page = val;
      this.getDetailList();
    },
    taskDetail_currentPage(val) {
      this.taskDetailListForm.taskDetail_page = val;
      this.getDetailList();
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.searchParam.per_page = val;
      this.getTasksList();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.searchParam.page = val;
      this.getTasksList();
    },
    //dialog close
    closeDialog(){
    }
  },
  filters:{
    textParseFilter(val){
      let text = '';
      if(val == 'pending'){
        text = '等待'
      }else if(val == 'stopped'){
        text = '暂停'
      } else if(val == 'finished'){
        text = '完成'
      } else if(val == 'success'){
        text = '成功'
      } else if(val == 'failed'){
        text = '失败'
      }
      return text;
    },
    colorParseFilter(val){
      let text = '';
      if(val == 'pending'){
        text = 'info'
      }else if(val == 'stopped'){
        text = 'warning'
      } else if(val == 'finished'){
        text = ''
      } else if(val == 'success'){
        text = 'success'
      } else if(val == 'failed'){
        text = 'danger'
      }
      return text;
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  .mainBox{
    padding: 0px;
    margin-bottom: 20px;
  }
  .container {
    margin: 10px 0px;
  }
</style>
